/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.trandio.manager;

import java.io.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import javax.swing.JOptionPane;

import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperCompileManager;

import net.sf.jasperreports.engine.JasperPrintManager;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.j2ee.servlets.ImageServlet;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;
import org.trandio.util.ConexionDb;
import org.trandio.util.Utiles;

/**
 *
 * @author root
 */
public class Reportes extends HttpServlet {

//Método que exporta el reporte en pdf
    private void exportPdf(HttpServletResponse response, String narchivo, Map param) throws IOException {
        // response.setContentType("application/pdf");

        /*
         * ServletOutputStream op = response.getOutputStream();
         *
         * JasperReport js; JasperPrint jp;
         *
         * try {
         *
         * ConexionDb con = new ConexionDb(); Connection cn; cn =
         * con.traerConexion();
         *
         * /*
         * final String jasperName =
         * JasperCompileManager.compileReportToFile(rutaRep + "/" + narchivo);
         * final JasperReport report = (JasperReport)
         * JRLoader.loadObject(jasperName); // Rellenamos el report pasándole al
         * informe la lista de parámetros y el datasource final JasperPrint
         * print = JasperFillManager.fillReport(report, param, cn);
         */
        /*
         * ServletContext sc = getServletConfig().getServletContext(); String
         * vjrxmlPath = "/WEB-INF/reportes/report1.jrxml"; String vjasperPath =
         * "/WEB-INF/reportes/report1.jasper";
         *
         * InputStream is = getResourceAsStream(vjasperPath);
         *
         * if (is == null) { String rp = sc.getRealPath(vjrxmlPath);
         * JasperCompileManager.compileReportToFile(rp); is =
         * sc.getResourceAsStream(vjasperPath); }
         *
         *
         *
         * /*
         * Creamos el objeto jasper print
         */
        /*
         * String jasperPath = sc.getRealPath(vjasperPath); JasperPrint jprint =
         * JasperFillManager.fillReport(jasperPath, param, cn);
         *
         * /*
         * Creamos el archivo xls
         */
        /*
         * String vxls = "/WEB-INF/reportes/detObjMet.xls"; String xls =
         * sc.getRealPath(vxls); JRXlsExporter exporter = new JRXlsExporter();
         * exporter.setParameter(JRExporterParameter.JASPER_PRINT, jprint);
         * exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, xls);
         * exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
         * Boolean.TRUE); exporter.exportReport();
         *
         * /*
         * Configuramos el tipo de archivo, la cabecera http
         */
        /*
         * File f = new File(xls);
         * response.setContentType("application/vnd.ms-excel");
         * response.setHeader("Content-Disposition", "attachment;filename=\"" +
         * "detObjMet.xls" + "\""); InputStream in = new FileInputStream(f);
         * ServletOutputStream sos = response.getOutputStream();
         *
         * int bit = 256; while ((bit) >= 0) { bit = in.read(); sos.write(bit);
         * }
         *
         * sos.flush(); sos.close(); in.close();
         *
         * } catch (JRException e) { StringWriter sw = new StringWriter();
         * PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw);
         * response.setContentType("text/plain");
         * response.getOutputStream().print(sw.toString()); } *
         *
         * //js = JasperCompileManager.compileReport(rutaRep + "/" + narchivo);
         * //jp = JasperFillManager.fillReport(js, param, cn);
         *
         * /* JRExporter exporter = new JRPdfExporter();
         * exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
         * exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, op);
         * exporter.exportReport();
         */

        /*
         * byte[] bites = JasperExportManager.exportReportToPdf(jp);
         * response.setHeader("Content-disposition", "attachment;
         * filename=Informe.pdf"); response.setContentLength(bites.length);
         * op.write(bites,0,bites.length); op.flush(); op.close();
         */

        /*
         * catch (Exception e) { JOptionPane.showMessageDialog(null, e); }
         */
    }
//exporta en html

    private void exportHtml(HttpServletResponse response, String dataSourceName, String narchivo, Map param) {
        //response.setContentType("text/html");
        //JasperReport js;
        //JasperPrint jp;

        /*
         * try { JRExporter exporter = null; Context inicon = new
         * InitialContext(); Context ctx = (Context)
         * inicon.lookup("java:comp/env"); DataSource ds = (DataSource)
         * ctx.lookup("jdbc/saludweb"); Connection cn = ds.getConnection();
         *
         * js = JasperCompileManager.compileReport("aa" + "\\" + narchivo); jp =
         * JasperFillManager.fillReport(js, param, cn); exporter = new
         * JRHtmlExporter();
         * exporter.setParameter(JRExporterParameter.JASPER_PRINT, jp);
         * exporter.setParameter(JRExporterParameter.OUTPUT_WRITER,
         * response.getWriter());
         * //exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI,
         * request.getContextPath() + "/image?image=");
         *
         * if (exporter != null) { exporter.exportReport(); } } catch (Exception
         * e) { JOptionPane.showMessageDialog(null, e); }
         */
    }

//exporta a xls
    private void exportXls(HttpServletResponse response, String dataSourceName, String narchivo, Map<String, Object> param) {

        try {

            Context inicon = new InitialContext();
            Context ctx = (Context) inicon.lookup("java:comp/env");
            DataSource ds = (DataSource) ctx.lookup("jdbc/saludweb");
            Connection cn = ds.getConnection();

            JasperReport report = JasperCompileManager.compileReport("aa" + "\\" + narchivo);
            JasperPrint print = JasperFillManager.fillReport(report, param, cn);
            ServletOutputStream out = response.getOutputStream();

            ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
            JRXlsExporter exporterXLS = new JRXlsExporter();

            exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, print);
            exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, arrayOutputStream);
            exporterXLS.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
            exporterXLS.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
            exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
            exporterXLS.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
            exporterXLS.exportReport();

            response.setHeader("Content-disposition", "attachment; filename=ListadoPDF");
            response.setContentType("application/vnd.ms-excel");
            response.setContentLength(arrayOutputStream.toByteArray().length);
            out.write(arrayOutputStream.toByteArray());
            out.flush();
            out.close();

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }

    }

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param requestre servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, NamingException, SQLException, JRException {
        ConexionDb con = new ConexionDb();
        Connection cn;
        cn = con.traerConexion();



        HttpSession session = request.getSession(true);
        String nombreLogo = (String) session.getAttribute("nombrelogo");
        String nombreLogoCom = "/imagenes/" + nombreLogo;


        Map parametros = new HashMap();

        int idfactura = Integer.parseInt(request.getParameter("idfactura"));
        parametros.put("idfactura", idfactura);

        InputStream img = getClass().getResourceAsStream(nombreLogoCom);

        //InputStream img =  getClass().getResourceAsStream(getServletConfig().getServletContext().getRealPath("WEB-INF/classes/imagenes/index.jpeg")); 
        parametros.put("logop", img);

        String val = request.getParameter("montofactura");


        String valorLetra = Utiles.convertirNumeroLetra(val, true);

        parametros.put("valorletra", valorLetra);


        ServletOutputStream servletOutputStream = response.getOutputStream();
        File reportFile = new File(getServletConfig().getServletContext().getRealPath("WEB-INF/reportes/report1.jasper"));
        byte[] bytes = null;
        try {
            bytes = JasperRunManager.runReportToPdf(reportFile.getPath(),
                    parametros, cn);
            response.setHeader("Content-Disposition", "inline; filename=reporte.pdf");
            response.setContentType("application/pdf");
            response.setContentLength(bytes.length);
            servletOutputStream.write(bytes, 0, bytes.length);
            servletOutputStream.flush();
            servletOutputStream.close();
        } catch (JRException e) {
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);
            e.printStackTrace(printWriter);
            response.setContentType("text/plain");
            response.getOutputStream().print(stringWriter.toString());
        }
    }

    /*
     * response.setHeader("Content-Disposition","inline; filename=reporte.pdf");
     * response.setContentType("application/pdf"); ServletOutputStream out =
     * response.getOutputStream(); ConexionDb con = new ConexionDb(); Connection
     * cn; cn = con.traerConexion(); try { JasperReport reporte = (JasperReport)
     * JRLoader.loadObject(getServletContext().getRealPath("WEB-INF/reportes/report1.jasper"));
     * Map parametros = new HashMap(); int idfactura =
     * Integer.parseInt(request.getParameter("idfactura"));
     * parametros.put("idfactura", idfactura);
     *
     *
     * JasperPrint jasperPrint = JasperFillManager.fillReport(reporte,
     * parametros, cn); JRExporter exporter = new JRPdfExporter();
     * exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
     * exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
     * exporter.exportReport(); } catch (Exception e) { e.printStackTrace(); }
     */
    /*
     * response.setContentType("application/pdf"); ServletOutputStream
     * out=response.getOutputStream();
     *
     * ConexionDb con = new ConexionDb();
     *
     * Connection cn;
     *
     * cn = con.traerConexion();
     *
     * Map parametros = new HashMap(); //JasperViewer jasperViewer = null;
     *
     * int idfactura = Integer.parseInt(request.getParameter("idfactura"));
     *
     *
     * parametros.put("idfactura", idfactura);
     *
     * String pdfFilePath =
     * getServletContext().getRealPath("WEB-INF/reportes/report1.pdf");
     *
     *
     * try {
     *
     * ServletContext ctx=this.getServletConfig().getServletContext(); String
     * filepath=getServletContext().getRealPath("WEB-INF/reportes/prueba.jrxml");
     * File jrxmlFile=new File(filepath); InputStream inputStream=new
     * FileInputStream(jrxmlFile); JasperReport
     * jasperReport=JasperCompileManager.compileReport(inputStream);
     *
     *
     * JasperPrint jasperPrint=JasperFillManager.fillReport(jasperReport,
     * parametros,cn);
     * JasperExportManager.exportReportToPdfFile(jasperPrint,pdfFilePath);
     * JasperExportManager.exportReportToPdfStream(jasperPrint, out);
     *
     *
     * }
     * catch(Exception e){ System.out.println("Exception occur"+e); } finally {
     * }
     *
     *
     *
     *
     *
     *
     *
     * }
     */
//jasperReport = JasperCompileManager.compileReport(getServletContext().getRealPath("WEB-INF/reportes/report1.jrxml"));
//jasperPrint = JasperFillManager.fillReport(jasperReport, parametros, cn);
//JasperExportManager.exportReportToPdfFile(jasperPrint, getServletContext().getRealPath("WEB-INF/reportes/report1.pdf"));
//cn.close();
//String nn = getServletContext().getRealPath("WEB-INF/reportes/report1.jasper");
//System.out.println(nn);
//JasperReport reporte = (JasperReport) JRLoader.loadObjectFromFile(getServletContext().getRealPath("WEB-INF/reportes/report1.jasper"));
//Map parametros = new HashMap();
//parametros.put("idfactura", 370);
//JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, cn);
//jasperViewer = new JasperViewer(jasperPrint, false); //generas tu visor del reporte
//jasperViewer.setTitle("Factura");
//jasperViewer.setVisible(true); //lo haces visible
            /*
     * JRExporter exporter = new JRPdfExporter();
     * exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
     * exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
     * exporter.exportReport();
     */
//} catch (Exception e) {
//    e.printStackTrace();
// }
//response.setContentType("text/html;charset=UTF-8");
//PrintWriter out = response.getWriter();
//try {
//Map param = new HashMap();
//param.put("idfactura", Integer.parseInt(request.getParameter("idfactura")));
//String tipo = request.getParameter("tipo");
//if (tipo.equals("pdf")) {
// this.exportPdf(response, "report1.jrxml", null);
//} else if (tipo.equals("xls")) {
//    this.exportXls(response, "jdbc/salus", "report1.jrxml", param);
//}
// } finally {
// out.close();
// }
// }
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            try {
                processRequest(request, response);






            } catch (JRException ex) {
                Logger.getLogger(Reportes.class.getName()).log(Level.SEVERE, null, ex);
            }






        } catch (NamingException ex) {
            Logger.getLogger(Reportes.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Reportes.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            try {
                processRequest(request, response);






            } catch (JRException ex) {
                Logger.getLogger(Reportes.class.getName()).log(Level.SEVERE, null, ex);
            }






        } catch (NamingException ex) {
            Logger.getLogger(Reportes.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Reportes.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
